﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CodeRepositoryConsole.FCL.IO
{
    public static class StringToTextFileDriver
    {
        public static void Test()
        {
            string destPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WriteToTxt.txt");
            StringToTextFile instance = new StringToTextFile();
            instance.WriteByStreamWriter(destPath, DateTime.Now.ToString() + "\t by StreamWrite");

            instance.WriteByWriteAllText(destPath, DateTime.Now.ToString() + "\t by ");
        }
    }

    class StringToTextFile
    {

        /// <summary>
        /// Creates a new file, writes the specified string to the file, and then closes the file. 
        /// If the target file already exists, it is overwritten.
        /// Write By WriteAllText
        /// </summary>
        /// <param name="path"></param>
        /// <param name="content"></param>
        /// <see cref="https://msdn.microsoft.com/en-us/library/ms143375.aspx"/>
        public void WriteByWriteAllText(string path, string content)
        {
            // remark
            // The method creates the file if it doesn’t exist, but it doesn't create new directories. 
            // Therefore, the value of the path parameter must contain existing directories.


            // This method uses UTF-8 encoding without a Byte-Order Mark (BOM), 
            // so using the GetPreamble method will return an empty byte array. 
            // If it is necessary to include a UTF-8 identifier, such as a byte order mark, 
            // at the beginning of a file, use the WriteAllText(String, String, Encoding) method overload with UTF8 encoding.
            // -- overwritten
            System.IO.File.WriteAllText(path, content + "WriteAllText");

            // new line
            System.IO.File.AppendAllLines(path,new string[] { content });

            // nor new line
            System.IO.File.AppendAllText(path, content);
        }

        /// <summary>
        /// Implements a TextWriter for writing characters to a stream in a particular encoding.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="content"></param>
        /// <see cref="https://msdn.microsoft.com/en-us/library/system.io.streamwriter(v=vs.110).aspx"/>
        public void WriteByStreamWriter(string path, string content)
        {
            // StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise.
            // This instance of UTF8Encoding is constructed without a byte order mark(BOM), 
            // so its GetPreamble method returns an empty byte array. 
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                sw.WriteLine(content);
            }
        }

    }
}
